import { ActionContext } from 'vuex'
import { fetchLogin } from '@/api/system/user'
import { setToken } from '@/utils/auth'
import { IUserState } from './state'
// import store from '@/store'
import { IStore } from '@/store/types'
interface IUserInfo {
  name: string
  password: string
}

export const actions = {
  /**
   * @description 登录
   */
  async login({ commit }: ActionContext<IUserState, IStore>, userInfo: IUserInfo) {
    try {
      const response = await fetchLogin(userInfo)
      const { code, data } = response

      if (code === 200) {
        commit('setToken', data.token)
        setToken(data.token)
      }

      return Promise.resolve(response)
    } catch (e) {
      return Promise.reject(e)
    }
  },

  /**
   * @description 退出登录
   */
  async logout({ commit }: ActionContext<IUserState, IStore>) {
    commit('setToken', '')
    commit('setRoles', [])
    commit('setUserInfo', '')
    return Promise.resolve(true)
  },
}
